<?php
session_start();

require_once("../database.include.php");
	
	$duplicate = "false";
	$myinvid=$_GET["myinv"];
	
	$sql = "SELECT `invitation_id`, `invited_user_name`,  `group_name`, `encrypted_group_private_key` FROM `group_invitation` WHERE `invitation_id` = '" . $myinvid . "'";
	foreach ($conn->query($sql) as $row) {
		$username = $row['invited_user_name'];
		$groupname = $row['group_name'];
		$encryptedGroupPrivateKey = $row['encrypted_group_private_key'];
	}

	// Already a member?
	$sql = "SELECT `group_name`, `user_name` FROM `group_user` WHERE `user_name` = '" . $username . "'";
	foreach ($conn->query($sql) as $row) {
		if ($row['group_name'] == $groupname) {
			$duplicate == "true";
		}
	}
	
	if ($duplicate == "false") {
		// Add to group_user
		$count = $conn->exec("INSERT INTO `group_user` (`group_name`, `user_name`, `encrypted_group_private_key`) VALUES ('" . $groupname . "', '" . $username . "', '" . encryptedGroupPrivateKey . "' )");
		echo "Added $count rows in group_user.\n";
	}
	
	// Delete invite from group_invitation
	$count = $conn->exec("DELETE FROM `group_invitation` WHERE `invitation_id` = '" . $myinvid . "'");
	/* Return number of rows that were deleted */
	echo "Deleted $count rows in group_invitation.\n";
?>
